#!/bin/bash

# 获取脚本所在目录的上级目录（项目根目录）
PROJECT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )"

# 检查配置文件是否存在
CONFIG_FILE="${PROJECT_DIR}/conf/nginx.conf"
if [ ! -f "$CONFIG_FILE" ]; then    
    echo "错误: 配置文件不存在: $CONFIG_FILE"
    exit 1
fi

# 检查 nginx 是否已运行
if pgrep -x "nginx" >/dev/null; then
    echo "检测到 nginx 正在运行。"
    read -p "是否重启 nginx？(y/n): " answer
    
    case $answer in
        [Yy]* )
            echo "正在停止 nginx..."
            nginx -s stop
            sleep 2  # 等待 nginx 完全停止
            
            # 再次检查是否还在运行
            if pgrep -x "nginx" >/dev/null; then
                echo "nginx 未能正常停止，是否强制终止？(y/n): "
                read force_kill
                if [ "$force_kill" = "y" ] || [ "$force_kill" = "Y" ]; then
                    echo "正在强制终止 nginx..."
                    pkill -9 nginx
                    sleep 1
                else
                    echo "取消强制终止操作"
                    exit 1
                fi
            fi
            ;;
        [Nn]* )
            echo "操作已取消"
            exit 1
            ;;
        * )
            echo "请输入 y 或 n"
            exit 1
            ;;
    esac
fi

# 启动 nginx
echo "正在启动 nginx..."
nginx -c "$CONFIG_FILE"

# 检查启动是否成功
if [ $? -eq 0 ] && pgrep -x "nginx" >/dev/null; then
    echo "Trading Hub 服务已成功启动"
    echo "配置文件路径: $CONFIG_FILE"
else
    echo "Trading Hub 服务启动失败，请检查配置文件和错误日志"
    exit 1
fi